package com.carey.blog.filter;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.framework.latke.Keys;
import com.carey.blog.repository.ArticleRepository;
import com.carey.blog.repository.impl.ArticleGAERepository;

/**
 * Article permalink filter.
 * 
 */
public final class ArticlePermalinkFilter implements Filter {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(ArticlePermalinkFilter.class.getName());
	/**
	 * Article repository.
	 */
	private ArticleRepository articleRepository = ArticleGAERepository
			.getInstance();

	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
	}

	/**
	 * Redirects request URI to {@link com.carey.blog.action.impl.ArticleAction}
	 * .
	 * 
	 * @param request
	 *            the specified request
	 * @param response
	 *            the specified response
	 * @param chain
	 *            filter chain
	 * @throws IOException
	 *             io exception
	 * @throws ServletException
	 *             servlet exception
	 */
	@Override
	public void doFilter(final ServletRequest request,
			final ServletResponse response, final FilterChain chain)
			throws IOException, ServletException {
		final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		final String requestURI = httpServletRequest.getRequestURI();
		LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);
		if (PageCacheFilter.shouldSkip(requestURI)) {
			LOGGER.log(Level.FINER, "Skip filter request[URI={0}]", requestURI);
			chain.doFilter(request, response);

			return;
		}

		try {
			final JSONObject article = articleRepository
					.getByPermalink(requestURI);
			if (null == article) {
				chain.doFilter(request, response);

				return;
			}

			final String articleId = article.getString(Keys.OBJECT_ID);

			final RequestDispatcher requestDispatcher = httpServletRequest
					.getRequestDispatcher("/article-detail.do");
			request.setAttribute(Keys.OBJECT_ID, articleId);
			requestDispatcher.forward(request, response);
		} catch (final Exception e) {
			((HttpServletResponse) response)
					.sendError(HttpServletResponse.SC_NOT_FOUND);

			return;
		}
	}

	@Override
	public void destroy() {
	}
}
